import configparser
import datetime
from datetime import datetime
import sys
from datetime import time
import time
from typing import Dict, Any
import jwt
from flask import Blueprint
from flask import jsonify,request, abort, make_response,render_template
import hashlib

from mongo.MongoHelper import MongoHelper
from tools.conf.confU import confU

# 创建一个Blueprint的实例
reg = Blueprint('reg', __name__)
database = confU().config.get('db', 'database')
myUrl = confU().config.get('db', 'url')
mongoHelper = MongoHelper(url=myUrl, database=database)
@reg.route('/')
def index():
    return jsonify({'message': 'Hello from my_api!'})


# curl -X  POST -H "Content-Type: application/json" -d '{"username":"test1", "password":"test1"}' http://localhost:6000/register
@reg.route('/register',  methods=['POST'])
def register():
    print('')
    password = request.json.get("password")
    username = request.json.get("username")
    encrypted = None
    if username is not None and password is not None and len(username)>0 and len(password)>0:
        coll = mongoHelper.mongo_db.get_collection('sysUsers')
        qCon: dict[str, Any] = {'username': username}
        result = coll.find_one(qCon)
        if result is None:
            m = hashlib.md5()
            m.update(password.encode("utf-8"))
            print(m.hexdigest())
            encrypted = m.hexdigest()
            record = {'username': request.json.get("username"), 'password': encrypted, 'status': 'Y', 'createdTime': datetime.now(),'source': '', 'cate': '1', 'cellphone': ''}
            cnt = coll.insert_one(record)
            print(f'{cnt.inserted_id}')
            return jsonify({'code':'0000','msg':'Success'})
        else:
            print(f'{username}已经存在至少一个')
            return jsonify({'code':'0001','msg':'existing'})
    else:
        return make_response('username not found', 404, {'WWW-Authenticate': 'Basic realm=""'})
